package com.wyl.auth.config;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2022/3/29 9:42
 */
@EnableOpenApi
@Configuration
@ConditionalOnBean(value = SwaggerProperty.class)
@Import(BeanValidatorPluginsConfiguration.class)
public class Knife4jConfiguration {

    @Autowired
    private SwaggerProperty swaggerProperty;

    @Bean(value = "swaggerDocket")
    public Docket defaultApi2() {
        Docket docket=new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //分组名称
                .groupName(swaggerProperty.getGroupName())
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage(swaggerProperty.getBasePackage()).and(RequestHandlerSelectors.withClassAnnotation(Api.class)))
                .paths(t->!t.equals("/error"))
                .build();

        // 开启头部请求
        List<RequestParameter> requestParameters = new ArrayList<>();
        RequestParameter requestParameter = new RequestParameterBuilder()
                .name("Authorization")
                .description("token")
                .required(false)
                .in(ParameterType.HEADER)
                .query(q->q.model(m->m.scalarModel(ScalarType.STRING)))
                .build();
        requestParameters.add(requestParameter);
        docket.globalRequestParameters(requestParameters);
        return docket;
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title(swaggerProperty.getTitle())
                .description(swaggerProperty.getDescription())
                .version(swaggerProperty.getVersion())
                .build();
    }
}
